package com.apcc4m.sfpush.handler;

import com.apcc4m.sfpush.SfpushConst;
import com.apcc4m.sfpush.bean.PushMessage;
import com.apcc4m.sfpush.listener.NettyServerListener;
import com.apcc4m.sfpush.service.MessageService;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>implements IChannelHandler {

    private ChannelHandlerContext ctx;
    private MessageService messageService;
    private NettyServerListener serverListener;
    public WebSocketFrameHandler(NettyServerListener serverListener, Class<?> serviceClass) {
        this.serverListener = serverListener;
        try {
            messageService = (MessageService) serviceClass.newInstance();
            messageService.init(serverListener, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive!!!!");
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    /**
     * user token验证成功后调用
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("userEventTriggered!!!!");
        super.userEventTriggered(ctx, evt);
    }

    @Override
    protected void messageReceived(ChannelHandlerContext arg0, TextWebSocketFrame frame) throws Exception {
        System.out.println("messageReceived!!!!" + frame.text());
        PushMessage msg = new PushMessage(frame.text());
        messageService.receive(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught!!!!");
        super.exceptionCaught(ctx, cause);
    }

    public void send(PushMessage msg) {
        ctx.channel().writeAndFlush(new TextWebSocketFrame(msg.toString()));
    }

    public void closeChannel() {
        String deviceId = ctx.channel().attr(SfpushConst.KEY_DEVICE_ID).get();
        serverListener.removeUserChannel(deviceId);
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        System.out.println("********handlerRemoved********");
    }

}
